package cn.chenfeifx.checker.thread;

import cn.chenfeifx.checker.CheckerApp;
import cn.chenfeifx.checker.eneity.MessageEntity;
import cn.chenfeifx.checker.eneity.Report;
import cn.chenfeifx.checker.enums.CheckerEnum;
import cn.chenfeifx.core.controls.CFTableView;
import com.alibaba.excel.util.StringUtils;
import javafx.scene.control.TableView;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class SplitRunable implements Runnable{

    private String filePath;
    private String reference;
    private String titleName;
    private String year;
    private Integer pageNumber;
    private String term;
    private String remark;
    private Integer caseNUmber;
    private Integer index;

    private String unitName = "01";


    private static final String[] CATALOG_LIST = {"一","二","三","4-1","4-2","4-3","4-4","五","六","七","八","9-1","9-2","9-3","9-4","十"};
    public SplitRunable(Integer index,
                        String reference,
                        String titleName,
                        String year,
                        Integer pageNumber,
                        String term,
                        String remark,
                        Integer caseNUmber,
                        String filePath) {
        this.index = index;
        this.reference = reference;
        this.remark = remark;
        this.term = term;
        this.year = year;
        this.titleName = titleName;
        this.pageNumber = pageNumber;
        this.caseNUmber = caseNUmber;
        this.filePath = filePath;
    }
    @Override
    public void run() {
        List<MessageEntity> messageList = new ArrayList<>();
        Set<Map<String,Integer>> numberset = new HashSet<>();
        List<String> newFilenames = new ArrayList<>();
        boolean issame = true;

        List<String> list = Arrays.asList(CATALOG_LIST);
        try {
            File file = new File(filePath + "/" + reference);
            FileInputStream excelFile = new FileInputStream(file+"/"+reference+".xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(excelFile);
            XSSFSheet sheet = workbook.getSheetAt(0);
            String parentCatalog = "";
            // 从第三行（索引为2）开始读取
            for (int rowIndex = 2; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row!= null) {
                    int lastCellNum = row.getLastCellNum();
                    for (int cellIndex = 0; cellIndex < lastCellNum; cellIndex++) {
                        Cell cell = row.getCell(cellIndex);
                        String stringCellValue = getCellValueAsString(cell).trim();
                        if(list.contains(stringCellValue)&&cellIndex==0){
                            parentCatalog = stringCellValue;
//                            System.out.println("父级目录：" + parentCatalog);
                        }
                        if(Pattern.matches("\\d+", stringCellValue)&&cellIndex==0){
                            String catalog = stringCellValue;
                            cell = row.getCell(6);
                            String pageNumber = getCellValueAsString(cell).trim();
                            if(StringUtils.isNotBlank(pageNumber)){
                                System.out.println("父级目录：" + parentCatalog +" 子目录："+catalog+" 页数："+pageNumber);
                                HashMap<String, Integer> map = new HashMap<>();
                                map.put(parentCatalog+"-"+catalog, Integer.valueOf(pageNumber));
                                numberset.add(map);
                            }
                        }
                    }
                }
            }
            List<Path> imagePaths = findImagesInFolder(filePath + "/" + reference);

            List<Path> sortedImagePaths = sortImagesByName(imagePaths);
            for (Map<String, Integer> map : numberset){
                for (Map.Entry<String, Integer> entry : map.entrySet()) {
                    String key = entry.getKey();
                    Integer value = entry.getValue();
                    for (int i = 0; i < value; i++){
                        String newname = "";
                        String[] split = key.split("-");
                        if(split.length==2){
                            split[0] = replaceString(split[0]);

                            if(split[0].length()==1){
                                newname = newname+"0";
                            }
                            newname = newname+split[0];

                            newname = newname+"00";

                            if(split[1].length()==1){
                                newname = newname+"00";
                            }
                            if(split[1].length()==2){
                                newname = newname+"0";
                            }
                            newname = newname+split[1];

                            if(i<99 && i>=9){
                                newname = newname+"0";
                            }else if(i<9){
                                newname = newname+"00";
                            }
                            newname = newname+ (i+1);

                        }else if(split.length==3){
                            split[0] = replaceString(split[0]);

                            if(split[0].length()==1){
                                newname = newname+"0";
                            }
                            newname = newname+split[0];

                            if(split[1].length()==1){
                                newname = newname+"0";
                            }
                            newname = newname+split[1];

                            if(split[2].length()==1){
                                newname = newname+"00";
                            }
                            if(split[2].length()==2){
                                newname = newname+"0";
                            }
                            newname = newname+split[2];


                            if(i<99 && i>=9){
                                newname = newname+"0";
                            }else if(i<9){
                                newname = newname+"00";
                            }

                            newname = newname+ (i+1);

                        }
                        newFilenames.add(newname+".jpg");
                    }

                }
            }



            int count = 0;
            if(newFilenames.size()!=sortedImagePaths.size()){
                issame = false;
                messageList.add(new MessageEntity(reference, "图片数量和件数不一致"));
            }else {
                newFilenames = sortImagesStrByName(newFilenames);
                for (String newname : newFilenames){
                    Path path = sortedImagePaths.get(count++);
                    System.out.println(path+""+newname);
                    fileRename(path,newname);
                }
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        for (MessageEntity messageEntity : messageList){
            System.out.println(messageEntity.getMessage());
            CheckerApp.getInstance().getMessageList(CheckerEnum.FILES.getCode()).add(messageEntity);
        }
        CFTableView cfTableView = CheckerApp.getInstance().getCfTableView();
        TableView tableView = cfTableView.getTableView();
        List<Report> items = tableView.getItems();
        Report report1 = items.get(index - 1);
        if(issame){
            report1.setStatusPath("/img/right.png");
        }else {
            report1.setStatusPath("/img/cha.png");
        }
        cfTableView.refresh();
    }

    private static String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                // 处理数字类型，包括日期（日期在Excel中也是以数字形式存储）
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    // 将日期格式化为字符串
                    Date date = cell.getDateCellValue();
                    java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    return dateFormat.format(date);
                } else {
                    double numericCellValue = cell.getNumericCellValue();
                    String result = String.format("%.0f", numericCellValue);
                    // 将数字转换为字符串
                    return result;
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                try {
                    // 计算公式并转换为字符串
                    return String.valueOf(cell.getNumericCellValue());
                } catch (Exception e) {
                    return cell.getStringCellValue();
                }
            default:
                return "";
        }
    }

    public static List<Path> findImagesInFolder(String folderPath) throws IOException {
        Path folder = Paths.get(folderPath);
        List<Path> allFiles = Files.walk(folder)
                .filter(Files::isRegularFile)
                .collect(Collectors.toList());

        List<Path> imageFiles = new ArrayList<>();
        for (Path file : allFiles) {
            String fileName = file.getFileName().toString();
            if (fileName.matches("\\d{3}\\.jpg")) { // 根据名称规则匹配，这里是四位数字.jpg格式
                imageFiles.add(file);
            }
        }
        return imageFiles;
    }

    public static String replaceString(String str) {
        str = str.replace("一", "1");
        str = str.replace("二", "2");
        str = str.replace("三", "3");
        str = str.replace("四", "4");
        str = str.replace("五", "5");
        str = str.replace("六", "6");
        str = str.replace("七", "7");
        str = str.replace("八", "8");
        str = str.replace("九", "9");
        str = str.replace("十", "10");
        return str;
    }

    public static List<Path> sortImagesByName(List<Path> imagePaths) {
        return imagePaths.stream()
                .sorted((p1, p2) -> {
                    String name1 = p1.getFileName().toString();
                    String name2 = p2.getFileName().toString();
                    return name1.compareTo(name2);
                })
                .collect(Collectors.toList());
    }

    public static List<String> sortImagesStrByName(List<String> imagePaths) {
        return imagePaths.stream()
                .sorted((p1, p2) -> {
                    String name1 = p1;
                    String name2 = p2;
                    return name1.compareTo(name2);
                })
                .collect(Collectors.toList());
    }

    public static void  fileRename(Path path,String newname ){
        Path targetPath = Paths.get(path.getParent()+"/"+newname); // 替换为实际的目标文件路径，仅文件名部分为新名称
        System.out.println("source:"+path+"target :"+targetPath);
        try {
            Files.move(path, targetPath);
            System.out.println("文件重命名成功！");
        } catch (IOException e) {
            System.out.println("文件重命名失败 源文件："+path+"新文件名:"+path.getParent()+"/"+newname);
//            System.err.println("文件重命名失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //new SplitRunable(1,"0001","张三","140000199901010011","/Users/zhangxin/doc/人事档案质检").run();
    }

}
